package javapop.framework;

public class ParseError extends DefaultParseResult<Object> {
	private String message;
	private boolean fatal;
	private ParseError child;
	
	public ParseError(ParseError child, String message, boolean fatal) {
		super(null,null);
		this.child = child;
		this.message  = message;
		this.fatal = fatal;
	}
	
	public ParseError(ParseError child, String message) {
		this(child,message,false);
	}

	public ParseError(String message, boolean fatal) {
		this(null,message,fatal);
	}

	public ParseError(String message) {
		this(null,message);
	}

	public ParseError getChild() {
		return child;
	}
	
	@Override
	public boolean checkType() {
		return true; // always of a correct type
	}
	
	@Override
	public void checkTypeWithExplanations() throws TypeError {
		// always a correct type
	}

	public void changeErrorMessage(String message) {
		this.message = message;
	}
	
	@Override
	public String getErrorMessage() {
		return message;
	}
	
	public void setFatal(boolean fatal) {
		this.fatal = fatal;
	}
	
	public boolean isFatal() {
		return fatal;
	}
	
	public ParseError cloneWithChild(ParseError child) {
		ParseError err = new ParseError(child,message,fatal);
		return err;
	}
	
	@Override
	public String getDetailedErrorMessage() {
		StringBuffer buf = new StringBuffer();
		buf.append("Parse error at Line ");
		buf.append(getStart().getLinePos());
		buf.append(" Char ");
		buf.append(getStart().getCharPos());
		buf.append("\n ==> ");
		buf.append(message);
		if(child!=null) {
			buf.append("\nFrom ");
			buf.append(child.getDetailedErrorMessage());
		}
		return buf.toString();
	}
	
	public boolean isError() {
		return true;
	}
	
	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append("ParseError[");
		buf.append("start="); buf.append(getStart());
		buf.append(",end="); buf.append(getEnd());
		buf.append(",fatal="); buf.append(isFatal());
		buf.append("{ \n");
		buf.append("  ");
		buf.append(getErrorMessage());
		buf.append("\n}");
		return buf.toString();
	}

}
